﻿using Learun.Util.SqlSugar;
using Learun.Util;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-06-21 15:32
    /// 描 述：箱柜表
    /// </summary>
    public class ec_PanelService
    {
        #region 仓储
        Repository<ec_projectEntity> _projectRepository => new Repository<ec_projectEntity>();
        Repository<ec_PanelEntity> _panelRepository => new Repository<ec_PanelEntity>();
        #endregion
        #region 获取数据
        /// <summary>
        /// 获取列表数据
        /// <summary>
        /// <returns></returns>
        public IEnumerable<ec_PanelEntity> GetList(string queryJson)
        {
            try
            {
                var ProjectEntity = new ec_projectEntity();
                //参考写法
                var queryParam = queryJson.ToJObject();
                var strSql = new StringBuilder();
                strSql.Append(@"SELECT t3.systempanel,t2.TagNumber,t.* ");
                if (queryParam["ProjectId"].IsEmpty())
                {
                    return null;
                }
                else
                {
                    //ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(queryParam["ProjectId"].ToString());
                    ProjectEntity = _projectRepository.GetById(queryParam["ProjectId"].ToString());
                    strSql.Append($"  FROM ec_panel_{ProjectEntity.ProjectIndex} t join ec_EngineData_{ProjectEntity.ProjectIndex} t2 on t.EngineerDataID=t2.EngineDataID ");
                    strSql.Append($"  join ec_objecttype_{ProjectEntity.ProjectIndex} t3 on t2.objecttypeID=t3.objecttypeID ");
                }
                strSql.Append(" WHERE 1=1 ");
                // 虚拟参数
                //var dp = new DynamicParameters(new { });
                var dp = new List<SugarParameter>();
                //if (!queryParam["EngineerDataID"].IsEmpty())
                //{
                //    dp.Add("EngineerDataID", queryParam["EngineerDataID"].ToString(), DbType.String);
                //    strSql.Append(" AND t.EngineerDataID = @EngineerDataID ");
                //}
                //return this.BaseRepository().FindList<ec_PanelEntity>(strSql.ToString(), dp);
                return SqlSugarHelper.Db.SqlQueryable<ec_PanelEntity>(strSql.ToString()).AddParameters(dp).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }



        /// <summary>
        /// 获取实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public ec_PanelEntity GetEntity(string ProjectId, string PanelID)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    return _panelRepository.GetById(PanelID);
                }
                else
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    var strSql = new StringBuilder();
                    strSql.Append($@" SELECT t3.objecttypename,T2.TAGNUMBER,T.* FROM ec_Panel_{ProjectEntity.ProjectIndex} t");
                    strSql.Append($@" LEFT JOIN ec_enginedata_{ProjectEntity.ProjectIndex} T2 ON T.EngineerDataID=T2.EngineDataID");
                    strSql.Append($"  left join ec_objecttype_{ProjectEntity.ProjectIndex} t3 on t2.objecttypeID=t3.objecttypeID ");
                    strSql.Append($" WHERE T.PanelID = '{PanelID}' or t.EngineerDataID='{PanelID}'");
                    //List<ec_PanelEntity> list = this.BaseRepository().FindList<ec_PanelEntity>(strSql.ToString()).ToList();
                    //return list.FirstOrDefault();
                    return SqlSugarHelper.Db.Ado.SqlQuerySingle<ec_PanelEntity>(strSql.ToString());
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 获取列表分页数据
        /// <param name="pagination">分页参数</param>
        /// <summary>
        /// <returns></returns>
        public IEnumerable<ec_PanelEntity> GetPageList(Pagination pagination, string queryJson)
        {
            try
            {
                var queryParam = queryJson.ToJObject();
                string ProjectId = queryParam["ProjectId"]?.ToString();
                string TagNumber = queryParam["TagNumber"]?.ToString();
                var tableName = ProjectSugar.TableName<ec_PanelEntity>(ProjectId);
                var enginedataTableName = ProjectSugar.TableName<ec_enginedataEntity>(ProjectId);
                var objecttypeTableName = ProjectSugar.TableName<ec_objecttypeEntity>(ProjectId);
                int records = 0;
                var list = _panelRepository.AsQueryable().AS(tableName)
                    .LeftJoin<ec_enginedataEntity>((a, b) => a.EngineerDataID == b.EngineDataID).AS<ec_enginedataEntity>(enginedataTableName)
                    .LeftJoin<ec_objecttypeEntity>((a, b, c) => b.ObjectTypeID == c.ObjectTypeID).AS<ec_objecttypeEntity>(objecttypeTableName)
                    .WhereIF(!string.IsNullOrEmpty(TagNumber), (a, b) => b.TagNumber.Contains(TagNumber))
                    .Select((a, b, c) => new ec_PanelEntity()
                    {
                        EngineerDataID = a.EngineerDataID,
                        MaxStripNumber = a.MaxStripNumber,
                        TagNumber = b.TagNumber,
                        systempanel = c.SystemPanel.ToString(),
                    })
                    .ToPageList(pagination.page, pagination.rows, ref records);
                pagination.records = records;
                return list;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        #endregion

        #region 提交数据

        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string ProjectId, string keyValue)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                var tableName = ProjectSugar.TableName<ec_PanelEntity>(ProjectId);
                var stripTableName = ProjectSugar.TableName<ec_PanelStripEntity>(ProjectId);
                var channelTableName = ProjectSugar.TableName<ec_PanelChannelEntity>(ProjectId);
                var termTableName = ProjectSugar.TableName<ec_PanelStripTermEntity>(ProjectId);

                //关联类型删除时，删除工程数据关联表记录。
                _panelRepository.AsDeleteable().AS(tableName).Where(x => x.PanelID == keyValue).ExecuteCommand();
                var existStrips = SqlSugarHelper.Db.Queryable<ec_PanelStripEntity>().AS(stripTableName).Where(x => x.PanelID == keyValue);
                var existStripIds = existStrips.Select(x => x.StripID).Distinct().ToList();
                SqlSugarHelper.Db.Deleteable<ec_PanelStripEntity>().AS(stripTableName).Where(x => x.PanelID == keyValue).ExecuteCommand();
                SqlSugarHelper.Db.Deleteable<ec_PanelChannelEntity>().AS(channelTableName).Where(x => existStripIds.Contains(x.StripID)).ExecuteCommand();
                SqlSugarHelper.Db.Deleteable<ec_PanelStripTermEntity>().AS(termTableName).Where(x => existStripIds.Contains(x.StripID)).ExecuteCommand();

                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(string ProjectId, string keyValue, ec_PanelEntity entity)
        {
            try
            {
                var ProjectEntity = new ec_projectEntity();
                if (!string.IsNullOrWhiteSpace(ProjectId))
                {
                    ProjectEntity = _projectRepository.GetById(ProjectId);
                }

                if (!string.IsNullOrEmpty(keyValue))
                {

                    entity.Modify(keyValue);
                    if (string.IsNullOrWhiteSpace(ProjectId))
                    {
                        _panelRepository.Update(entity);
                    }
                    else
                    {
                        //this.BaseRepository().UpdateByNoMap(entity, $"ec_Panel_{ProjectEntity.ProjectIndex}", "PanelID");
                        _panelRepository.AsUpdateable(entity).AS($"ec_Panel_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }


                }
                else
                {
                    entity.Create();
                    if (string.IsNullOrWhiteSpace(ProjectId))
                    {
                        _panelRepository.Insert(entity);
                    }
                    else
                    {
                        //this.BaseRepository().InsertByNoMap(entity, $"ec_Panel_{ProjectEntity.ProjectIndex}");
                        _panelRepository.AsInsertable(entity).AS($"ec_Panel_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        #endregion

    }
}
